package com.lc.activiti.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lc.activiti.config.Result;
import com.lc.activiti.sys.dao.SysUserRoleDao;
import com.lc.activiti.sys.entity.SysUserRole;
import com.lc.activiti.sys.service.SysUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 人员角色关系(SysUserRole)表服务实现类
 *
 * @author 骆超
 * @since 2021-06-28 15:37:20
 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRole> implements SysUserRoleService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveUserRole(SysUserRole sysUserRole) {
        List<SysUserRole> sysUserRoleList = new ArrayList<>();
        //首先移除用户原有的角色
        remove(Wrappers.lambdaQuery(SysUserRole.class).eq(SysUserRole::getUserId,sysUserRole.getUserId()));
        sysUserRole.getRoleIds().forEach(v -> sysUserRoleList.add(new SysUserRole().setUserId(sysUserRole.getUserId()).setRoleId(v)));
        if (!sysUserRoleList.isEmpty()) {
            //批量保存新角色
           return Result.success(saveOrUpdateBatch(sysUserRoleList));
        }
        return Result.failed("配置用户角色失败！");
    }
}
